package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.entity.*;
import com.api.shopapi.service.AreaService;
import com.api.shopapi.service.ElderlyService;
import com.api.shopapi.service.UserAddressService;
import com.api.shopapi.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * 用户地址
 * */

@RequestMapping("UserAddress")
@RestController
public class UserAddressController extends BaseController {

    @Autowired
    @Qualifier("UserAddressServiceImplOne")
    private UserAddressService userAddressService;

    @Autowired
    @Qualifier("AreaServiceImplOne")
    private AreaService areaService;

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    String name = "";





    //查询所有信息
    @RequestMapping(value = "List", method = RequestMethod.POST)
    public MyResult List(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode=jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/UserAddress/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<UserAddress> listUserAddress =userAddressService.getList();
            return success(listUserAddress);
        } catch (Exception e) {
            insertError("/UserAddress/List",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //添加
    @RequestMapping(value = "Add2",method = RequestMethod.POST)
    public MyResult Add2(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode=jsonObject.getString("userCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/Add2");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String userAddressCode=UUID.randomUUID().toString();
            String receiveName=jsonObject.getString("receiveName");
            String receivePhone=jsonObject.getString("receivePhone");
            String receiveAddress=jsonObject.getString("receiveAddress");
            String areaCode=jsonObject.getString("areaCode");


            Area area = areaService.getByAreaCode(areaCode);

            //递归查询地址
            String an= getByAreaCode(areaCode);
            String areaNamePath = an.substring(0,an.length()-1);
            //System.out.println("返回："+getByAreaCode(areaCode));

            UserAddress userAddress =new UserAddress();
            userAddress.setUserAddressCode(userAddressCode);
            userAddress.setUserCode(userCode);
            userAddress.setReceiveName(receiveName);
            userAddress.setReceivePhone(receivePhone);
            userAddress.setReceiveAddress(receiveAddress);
            userAddress.setAreaCode(areaCode);
            userAddress.setAreaName(area.getName());
            userAddress.setAreaNamePath(areaNamePath);
            userAddressService.insert(userAddress);

            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/UserAddress/Add2",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //添加
    @RequestMapping(value = "Add",method = RequestMethod.POST)
    public MyResult Add(@RequestBody JSONObject jsonObject){

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode=jsonObject.getString("userCode");
//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            name = "";
            String userAddressCode=UUID.randomUUID().toString();
            String receiveName=jsonObject.getString("receiveName");
            String receivePhone=jsonObject.getString("receivePhone");
            String receiveAddress=jsonObject.getString("receiveAddress");
            String areaCode=jsonObject.getString("areaCode");
            Area area = areaService.getByAreaCode(areaCode);
            //递归查询地址
            String an= getByAreaCode(areaCode);
            String areaNamePath = an.substring(0,an.length()-1);
            UserAddress userAddress =new UserAddress();
            userAddress.setUserAddressCode(userAddressCode);
            userAddress.setUserCode(userCode);
            userAddress.setReceiveName(receiveName);
            userAddress.setReceivePhone(receivePhone);
            userAddress.setReceiveAddress(receiveAddress);
            userAddress.setAreaCode(areaCode);
            userAddress.setAreaName(area.getName());
            userAddress.setAreaNamePath(areaNamePath);

            userAddressService.insert(userAddress);

            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/UserAddress/Add",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }


    }


    //查询地址
    public String getByAreaCode(String areaCode){
        Area area = areaService.getByAreaCode(areaCode);
        if(area == null){
           return name;
        }else {
            String parentAreaCode = area.getParentAreaCode();
            name = area.getName()+","+name;
            getByAreaCode(parentAreaCode);
        }
        return name;
    }

    //列表
    @RequestMapping(value = "Page",method = RequestMethod.POST)
    public MyResult Page(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode=jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/UserAddress/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            int pageIndex =jsonObject.getInteger("pageIndex");
            int pageSize =jsonObject.getInteger("pageSize");

            PageInfo<UserAddress> pageInfoUserAddress =userAddressService.getPageInfo(pageIndex,pageSize);
            return success(pageInfoUserAddress);

        } catch (Exception e) {
            insertError("/UserAddress/Page",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //编辑
    @RequestMapping(value = "Edit",method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode=jsonObject.getString("userCode");

            String userAddressCode=jsonObject.getString("userAddressCode");
            String receiveName=jsonObject.getString("receiveName");
            String receivePhone=jsonObject.getString("receivePhone");
            String receiveAddress=jsonObject.getString("receiveAddress");
            String areaCode=jsonObject.getString("areaCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            name="";
            Area area = areaService.getByAreaCode(areaCode);

            //递归查询地址
            String an= getByAreaCode(areaCode);
            String areaNamePath = an.substring(0,an.length()-1);
            //System.out.println("返回："+getByAreaCode(areaCode));


            UserAddress userAddress=userAddressService.getByUserAddressCode(userAddressCode);
            if(userAddress==null){
                return failed("地址不存在");
            }

//            String areaName = userAddress.getAreaName();
//            if(!userAddress.getAreaCode().equals(areaCode)){
//                String an= getByAreaCode(areaCode);
//                areaName = an.substring(0,an.length()-1);
//            }

            userAddress.setUserCode(userCode);
            userAddress.setReceiveName(receiveName);
            userAddress.setReceivePhone(receivePhone);
            userAddress.setReceiveAddress(receiveAddress);
            userAddress.setAreaCode(areaCode);
            userAddress.setAreaName(area.getName());
            userAddress.setAreaNamePath(areaNamePath);
            userAddressService.update(userAddress);

            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/UserAddress/Edit",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //获取个人地址列表
    @RequestMapping(value = "GetMyAddress",method = RequestMethod.POST)
    public  MyResult GetMyAddress(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode=jsonObject.getString("userCode");
//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/GetMyAddress");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<UserAddress> userAddressList =userAddressService.getMyAddressList(userCode);

            return success(userAddressList);
        } catch (Exception e) {
            insertError("/UserAddress/GetMyAddress",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "Delete", method = RequestMethod.POST)
    public MyResult delete(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userAddressCode=jsonObject.getString("userAddressCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/Delete");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            UserAddress userAddress = userAddressService.getByUserAddressCode(userAddressCode);
            if (userAddress == null) {
                return failed("地址不存在");
            } else {
                userAddressService.delete(userAddressCode);
            }
            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/UserAddress/Delete",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //修改默认地址
    @RequestMapping(value = "AddressSetDefault", method = RequestMethod.POST)
    public MyResult addressSetDefault(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            String userAddressCode=jsonObject.getString("userAddressCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/AddressSetDefault");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            userAddressService.addressSetDefault0(userCode);
            int c = userAddressService.addressSetDefault1(userAddressCode);
            if(c==0){
                return failed("修改失败");
            }
            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/UserAddress/AddressSetDefault",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }








    //老人的地址列表(预订单)
    @RequestMapping(value = "ListForStaff",method = RequestMethod.POST)
    public  MyResult GetMyAddressForStaff(@RequestBody JSONObject jsonObject){
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode=jsonObject.getString("staffCode");
            String elderlyCode=jsonObject.getString("elderlyCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/ListForStaff");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            User user = userService.getByUserCode(elderly.getUserCode());

            List<UserAddress> userAddressList =userAddressService.getMyAddressList(user.getUserCode());
            return success(userAddressList);
        } catch (Exception e) {
            insertError("/UserAddress/ListForStaff",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //添加(预订单)
    @RequestMapping(value = "AddForStaff",method = RequestMethod.POST)
    public MyResult AddForStaff(@RequestBody JSONObject jsonObject){

        try {

            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode=jsonObject.getString("staffCode");
            String elderlyCode=jsonObject.getString("elderlyCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/AddForStaff");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String userAddressCode=UUID.randomUUID().toString();
            String receiveName=jsonObject.getString("receiveName");
            String receivePhone=jsonObject.getString("receivePhone");
            String receiveAddress=jsonObject.getString("receiveAddress");
            String areaCode=jsonObject.getString("areaCode");


            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            User user = userService.getByUserCode(elderly.getUserCode());


            Area area = areaService.getByAreaCode(areaCode);

            //递归查询地址
//            String an= getByAreaCode(areaCode);
//            String areaNamePath = an.substring(0,an.length()-1);
            //System.out.println("返回："+getByAreaCode(areaCode));
            String areaNamePath =getAreaName(areaCode,"");


            UserAddress userAddress =new UserAddress();
            userAddress.setUserAddressCode(userAddressCode);
            userAddress.setUserCode(user.getUserCode());
            userAddress.setReceiveName(receiveName);
            userAddress.setReceivePhone(receivePhone);
            userAddress.setReceiveAddress(receiveAddress);
            userAddress.setAreaCode(areaCode);
            userAddress.setAreaName(area.getName());
            userAddress.setAreaNamePath(areaNamePath);
            userAddressService.insert(userAddress);

            Object object = new Object[]{};
            return success(object);

        } catch (Exception e) {
            insertError("/UserAddress/AddForStaff",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //编辑(预订单)
    @RequestMapping(value = "EditForStaff",method = RequestMethod.POST)
    public MyResult EditForStaff(@RequestBody JSONObject jsonObject){

        try {

            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode=jsonObject.getString("staffCode");
            String elderlyCode=jsonObject.getString("elderlyCode");

            String userAddressCode=jsonObject.getString("userAddressCode");
            String receiveName=jsonObject.getString("receiveName");
            String receivePhone=jsonObject.getString("receivePhone");
            String receiveAddress=jsonObject.getString("receiveAddress");
            String areaCode=jsonObject.getString("areaCode");

//            if (!checkSignPC(timeStr, sign)) {
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/UserAddress/EditForStaff");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            User user = userService.getByUserCode(elderly.getUserCode());

            Area area = areaService.getByAreaCode(areaCode);

            String areaNamePath=getAreaName(areaCode,"");
            //递归查询地址
//            String an= getByAreaCode(areaCode);
//            String areaNamePath = an.substring(0,an.length()-1);
            //System.out.println("返回："+getByAreaCode(areaCode));


            UserAddress userAddress=userAddressService.getByUserAddressCode(userAddressCode);
            if(userAddress==null){
                return failed("地址不存在");
            }

            userAddress.setUserCode(user.getUserCode());
            userAddress.setReceiveName(receiveName);
            userAddress.setReceivePhone(receivePhone);
            userAddress.setReceiveAddress(receiveAddress);
            userAddress.setAreaCode(areaCode);
            userAddress.setAreaName(area.getName());
            userAddress.setAreaNamePath(areaNamePath);
            userAddressService.update(userAddress);

            Object object = new Object[]{};
            return success(object);

        } catch (Exception e) {
            insertError("/UserAddress/EditForStaff",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    public String getAreaName(String areaCode, String areaName) {
        Area area = areaService.getByAreaCode(areaCode);
        if (area != null) {
            if (areaName == "") {
                areaName = area.getName();
            } else {
                areaName = area.getName() + "," + areaName;
            }
            areaName = getAreaName(area.getParentAreaCode(), areaName);
        }
        return areaName;
    }






}
